// Package ip ip操作相关函数
package ip

import (
	"fmt"
	"gitee.com/dingyangzhuang/dingutils/dlog/logger"
	"net"
	"strconv"
	"strings"
)

// GetHostIpFromUDP 通过udp访问自己来获取主机IP
func GetHostIpFromUDP() string {
	conn, err := net.Dial("udp", "8.8.8.8:53")
	if err != nil {
		fmt.Println("get current host ip err: ", err)
		return ""
	}
	addr := conn.LocalAddr().(*net.UDPAddr)
	ip := strings.Split(addr.String(), ":")[0]
	return ip
}

// GetHostIp 通过接口获取IP，获取第一个IP
func GetHostIp() string {
	addrList, err := net.InterfaceAddrs()
	if err != nil {
		fmt.Println("get current host ip err: ", err)
		return ""
	}
	var ip string
	for _, address := range addrList {
		if ipNet, ok := address.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
			if ipNet.IP.To4() != nil {
				ip = ipNet.IP.String()
				break
			}
		}
	}
	return ip
}

// GetHostIpFilter 查询接口IP,获取相关前缀的IP
//
// 参数 ipPrefix：IP前缀
func GetHostIpFilter(ipPrefix string) string {
	addrList, err := net.InterfaceAddrs()
	if err != nil {
		fmt.Println("get current host ip err: ", err)
		return ""
	}
	var ip string
	for _, address := range addrList {
		if ipNet, ok := address.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
			if ipNet.IP.To4() != nil && strings.Contains(ipNet.IP.To4().String(), ipPrefix) {
				ip = ipNet.IP.String()
				break
			}
		}
	}
	return ip
}

/*
*
10.124.61.200-223
10.124.61.224-226
10.124.61.175-179
将这种格式的IP展开
*/
func IpFlat(ips string) string {
	line := strings.Split(ips, "\n")
	builder := strings.Builder{}
	for _, iprange := range line {
		ipranges := strings.Split(iprange, "-")
		startip := ipranges[0]
		startips := strings.Split(startip, ".")
		if len(startips) < 3 {
			continue
		}
		startips = startips[:3]

		prefixs := strings.Join(startips, ".")
		start_num, err := strconv.Atoi(strings.Split(startip, ".")[3])
		if err != nil {
			logger.Error(err.Error())
			return ""
		}
		end_num, err := strconv.Atoi(ipranges[1])
		if err != nil {
			logger.Error(err.Error())
			return ""
		}
		builder.WriteString(startip + "\n")
		for start_num < end_num {
			start_num += 1
			builder.WriteString(prefixs + "." + fmt.Sprint(start_num) + "\n")
		}
	}
	return builder.String()
}
